//
//  Extension.swift
//  AIPosts
//
//  Created by 张昭 on 2024/7/14.
//

import UIKit
import CommonCrypto

extension UIColor {

    public convenience init(_ hexValue: Int, alpha: CGFloat = 1.0) {
        let redValue   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
        let greenValue = CGFloat((hexValue & 0xFF00) >> 8) / 255.0
        let blueValue  = CGFloat(hexValue & 0xFF) / 255.0
        self.init(red: redValue, green: greenValue, blue: blueValue, alpha: alpha)
    }
    
    public static func MainColor() -> UIColor {
        return UIColor(0xF8DD2D)
    }
}

extension UIButton {
    
    func takeImageAboveTitle(_ spacing: CGFloat) {
        guard let image = self.imageView?.image else { return }
        guard let titleLabel = self.titleLabel else { return }
        let imageSize = image.size
        let titleSize = titleLabel.intrinsicContentSize
        self.imageEdgeInsets = UIEdgeInsets(
            top: -(titleSize.height + spacing / 2),
            left: 0,
            bottom: 0,
            right: -titleSize.width
        )
        self.titleEdgeInsets = UIEdgeInsets(
            top: 0,
            left: -imageSize.width,
            bottom: -(imageSize.height + spacing / 2),
            right: 0
        )
        let contentHeight = imageSize.height + titleSize.height + spacing
        self.contentEdgeInsets = UIEdgeInsets(
            top: (self.frame.height - contentHeight) / 2,
            left: 0,
            bottom: (self.frame.height - contentHeight) / 2,
            right: 0
        )
    }
}

extension UINavigationController {
    
    func makeNavigationBarTransparent() {
        // 设置背景透明
        navigationBar.setBackgroundImage(UIImage(), for: .default)
        // 移除高斯模糊效果
        navigationBar.shadowImage = UIImage()
        navigationBar.isTranslucent = true
        // 移除模糊背景视图
        if let visualEffectView = navigationBar.subviews.first(where: { $0 is UIVisualEffectView }) {
            visualEffectView.removeFromSuperview()
        }
        // 确保背景色为透明
        navigationBar.backgroundColor = .clear
        // 确保没有其他背景视图
        navigationBar.subviews.forEach { subview in
            if subview != navigationBar.topItem?.titleView {
                subview.backgroundColor = .clear
            }
        }
    }
}

extension UIImage {
    
    @objc public static func color(_ color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 10, height: 10)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

extension UIView {
    
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

func attributedStringFromHTML(_ html: String, completion: ((NSAttributedString?) -> Void)? = nil) {
    DispatchQueue.global(qos: .userInitiated).async {
        guard let data = html.data(using: .utf8) else {
            DispatchQueue.main.async {
                completion?(nil)
            }
            return
        }
        
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]
        
        let attributedString: NSAttributedString?
        do {
            attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil)
        } catch {
            attributedString = nil
        }
        DispatchQueue.main.async {
            App.shared.attributedItems[html.MD5] = attributedString
            completion?(attributedString)
        }
    }
}

extension String {
    
    var MD5: String {
        let cStr = cString(using: .utf8)!
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16)
        CC_MD5(cStr, (CC_LONG)(strlen(cStr)), buffer)
        var md5Result = ""
        for i in 0 ..< 16 {
            md5Result = md5Result.appendingFormat("%02x", buffer[i])
        }
        free(buffer)
        return md5Result
    }
}

extension UITabBar {
    
    func setItemTitleColor(_ color: UIColor, selectedColor: UIColor) {
        let appearance = UITabBarAppearance()
        let normalAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: color
        ]
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = normalAttributes
        let selectedAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: selectedColor
        ]
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = selectedAttributes
        self.standardAppearance = appearance
        self.scrollEdgeAppearance = appearance
    }
}
